<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="../../../Themes/default/easyui.css">
		<link rel="stylesheet" type="text/css" href="../../../Themes/icon.css">
		<link rel="stylesheet" type="text/css" href="../../../CSS/demo.css">
		<link rel="stylesheet" type="text/css" href="../../../CSS/common.css">
	</head>

	<body style="padding:0px">
		<div id="toolbar" class="receipts_toolbar_style"></div>
		<div>
			<div style="float: right;margin-top: 0px;max-width:60px;" id="notreview"></div>
			<form id="ff" action="#" method="post">
				<table cellpadding="5" class="displaytable" style="text-align: left;width: 80%;height: 80px;margin: 0 auto;">
					<tr>
						<td width="13%">
							<h id="star">* </h>建单人</td>
						<td width="20%">
							<input class="easyui-combobox" style="width: 100%;" type="text" name="CREATE_MAN" id="input_CREATE_MAN" data-options="prompt:'由系统自动生成，不需填写',disabled:true"></input>
						</td>
						<td width="13%">
							<h id="star">* </h>建单时间</td>
						<td width="20%">
							<input class="easyui-datebox" style="width:100%;" type="text" name="CREATE_TIME" id="input_CREATE_TIME" data-options="prompt:'由系统自动生成，不需填写',disabled:true" />
						</td>
						<td width="13%">
							<h id="star">* </h>冲销单编号</td>
						<td width="20%">
							<input class="easyui-textbox" style="width: 100%" type="text" name="ORDER_NO" id="input_ORDER_NO" data-options="prompt:'由系统自动生成，不需填写',disabled:true" />
						</td>
					</tr>
				</table>
				<table id="tt">

				</table>
				<div style="margin-left: 20%;" id="new_footer">

				</div>
			</form>
		</div>
	</body>
	<script type="text/javascript" src="../../../JS/jquery.min.js"></script>
	<script type="text/javascript" src="../../../JS/jquery.easyui.min.js"></script>
	<script type="text/javascript" src="../../../JS/common.js"></script>
	<script type="text/javascript" src="../../../JS/finance.js"></script>
	<script type="text/javascript" src="../../../JS/jquery.edatagrid.js"></script>
	<script type="text/javascript" src="../../../JS/SHA-1.js"></script>
	<script type="text/javascript" src="../../../JS/addRowShareFunction.js"></script>
	<script type="text/javascript">
		var currid = AddFlag;
		var id = getID();
		var currPage = 0;
		var MaxPage = 0;
		var MinPage = 1;
		var currRow;
		var isVerify;
		var content = "";
		var storehousename;
		var _detailToolbarData;
		var _dataPage;
		var updateData;
		_detailToolbarData = AddDetailToolBar(7);
		$(document).ready(function(){
			if(id != AddFlag && id != undefined) {
			currid = id;
			loadRemote();
		}
		});
		
		//增加脚注
		getPageMaxAndMin();
		addFooter($("#new_footer"));

		var receipts_type = RECEIPT_FRONT_SYMBOL;
		receipts_type += RECEIPT_NEXT_SYMBOL;
		receipts_type += RECEIPT_ADD_SYMBOL;
		receipts_type += RECEIPT_SAVE_SYMBOL;
		receipts_type += RECEIPT_DELETE_SYMBOL;
		receipts_type += RECEIPT_VERIFY_SYMBOL;
		receipts_type += RECEIPT_UNVERIFY_SYMBOL;
		receipts_type += RECEIPT_PRINT_SYMBOL;
		receipts_type += RECEIPT_SEARCH_SYMBOL;
		receipts_type += RECEIPT_EXPORT_SYMBOL;
		content = AddReceiptsToolBar(receipts_type, "");
		$("#toolbar").append(content);

		GetDetailTable();
		$('#tt').datagrid('hideColumn', 'ID');
		$('#tt').datagrid('hideColumn', 'ORDER_ID');
		$('#tt').datagrid('hideColumn', 'STOREHOUSE_ID');
		$('#tt').datagrid('hideColumn', 'INTERNALTRADE_ID');

		function getPageMaxAndMin() {
			var _url = RemoteLinkAddress + "/logistics/writeoff/getmaxminid.do";
			$.ajax({
				type: "get",
				url: _url,
				dataType: "json",
				success: function(result) {
					if(result != null) {
						MaxPage = result.MAXID;
						MinPage = result.MINID;
						currPage = result.MINID + 1;
					}
				},
				error: function(xhr, status, error) {
					$.messager.alert("错误", "请求失败!");
				}
			});
		}

		function loadRemote() {
			var _url = RemoteLinkAddress + '/logistics/writeoff/findbyid.do?ID=' + currid;
			getRemoteData(_url);
		}

		function getRemoteData(_url) {
			$.ajax({
				type: "get",
				url: _url,
				dataType: "json",
				success: function(result) {
					console.log(result);
					if(result != null) {
						_dataPage = result;
						isVerify = result.ISVERIFY;
						verifyStatus(result.ISVERIFY, true);
						updateData = deepCopy(result);
						getFormData(result);
						currPage = result.ID;
						currid = result.ID;
						var _data = result.rows;
						for(var i = 0; i < _data.length; i++) {
							if(_data[i].TYPE == 0) {
								_data[i].TYPE = "冲正";
							} else {
								_data[i].TYPE = "冲负";
							}
						}
						$('#tt').edatagrid('loadData', _data);
					}
				},
				error: function(xhr, status, error) {
					$.messager.alert("错误", "请求失败!");
				}
			});
		}

		//单据的相关功能
		function frontpage() { //上一张
			if(currPage > MinPage) {
				var _url = RemoteLinkAddress + '/logistics/writeoff/pre.do?ID=' + currPage;
				getRemoteData(_url);
			} else {
				$.messager.alert("提示", "没有上张");
			}
		}

		function nextpage() { //下一张
			if(currPage < MaxPage) {
				var _url = RemoteLinkAddress + '/logistics/writeoff/next.do?ID=' + currPage;
				getRemoteData(_url);
			} else {
				$.messager.alert(" 提示", "没有下张");
			}
		}

		function newdata() {
			currid = AddFlag;
			currPage = 0;
			$("#input_CREATE_MAN").textbox("setValue", "");
			$("#input_CREATE_TIME").datebox("setValue", "");
			$("#input_ORDER_NO").textbox("setValue", "");
			$('#tt').datagrid('loadData', {
				total: 0,
				rows: []
			});
			$('#notreview').empty();
		}

		function save() { //保存
			if(currid != AddFlag && isVerify == "1") {
				$.messager.alert('警告', '该单据已通过审核，不可修改！');
				return;
			}
			if($("#tt").datagrid('getRows').length == 0) {
				$.messager.alert('警告', '表格数据不可为空！');
				return;
			}
			if(currid != AddFlag) {
				getUpdateData();
			} else {
				getSaveData();
			}
		}

		function getUpdateData() {
			updateData.CREATE_MAN = $("input[name='CREATE_MAN']").val();
			updateData.CREATE_TIME = $("input[name='CREATE_TIME']").val();
			updateData.ORDER_NO = $("input[name='ORDER_NO']").val();
			updateData.rows = new Array();
			var dataGridRows = $("#tt").datagrid("getRows");
			var _index = 0;
			for(var i = 0; i < dataGridRows.length; i++) {
				updateData.rows[_index] = new Object();
				updateData.rows[_index].ID = dataGridRows[i].ID;
				updateData.rows[_index].ORDER_ID = dataGridRows[i].ORDER_ID;
				updateData.rows[_index].STOREHOUSE_ID = dataGridRows[i].STOREHOUSE_ID;
				updateData.rows[_index].INTERNALTRADE_ID = dataGridRows[i].INTERNALTRADE_ID;
				updateData.rows[_index].OLDSTOCK = dataGridRows[i].OLDSTOCK;
				if(dataGridRows[i].TYPE == "冲正") {
					updateData.rows[_index].TYPE = 0;
				} else {
					updateData.rows[_index].TYPE = 1;
				}
				updateData.rows[_index].WRITEOFFSTOCK = dataGridRows[i].WRITEOFFSTOCK;
				_index++;
			}
			submitData(updateData);
		}

		function getSaveData() {
			var data = new Object();
			data.CREATE_MAN = $("input[name='CREATE_MAN']").val();
			data.CREATE_TIME = $("input[name='CREATE_TIME']").val();
			data.ORDER_NO = $("input[name='ORDER_NO']").val();
			data.MEMO = $("input[name='MEMO']").val();
			data.rows = new Array();
			var _data = $('#tt').datagrid('getRows');
			for(var i = 0; i < _data.length; i++) {
				if(_data[i].TYPE == "冲正") {
					_data[i].TYPE = 0;
				} else {
					_data[i].TYPE = 1;
				}
			}
			data.rows = _data;
			submitData(data);
		}

		function submitData(_data) {
			var _url = "";
			if(currid == AddFlag) {
				_url = RemoteLinkAddress + "/logistics/writeoff/save.do";
			} else {
				_url = RemoteLinkAddress + "/logistics/writeoff/update.do";
			}
			var _senddata = JSON.stringify(_data);
			$.ajax({
				dataType: 'JSON',
				url: _url,
				data: 'a=' + _senddata,
				type: "POST",
				success: function(result) {
					if(currid == AddFlag) {
						var revData = result.msg.split(";");
						$("#input_ORDER_NO").textbox("setValue", revData[2]);
						$("#input_CREATE_MAN").combobox("setValue", revData[3]);
						$("#input_CREATE_TIME").datebox("setValue", revData[4]);
						$.messager.alert("提示", "新建保存成功");
						currPage = revData[1];
						currid = revData[1];
						return;
					}
					$.messager.alert("提示", "修改保存成功");
				},
				error: function(result) {
					$.messager.alert("错误", "保存失败");
				}
			});
		}

		function deletedata() { //删除
			if(currid != AddFlag && isVerify == 1) {
				$.messager.alert('警示', "该单据已审核，不可以删除！");
				return;
			}
			if(currid == AddFlag) {
				$.messager.alert('警示', "当前页面为新增页面，不能删除！");
				return;
			}
			$.messager.confirm('Confirm', '是否删除', function(r) {
				if(r) {
					$.post(RemoteLinkAddress + "/logistics/writeoff/delete.do", {
							ID: currid,
						},
						function(result) {
							if(result.msg == "success") {
								$('#tt').datagrid('reload');
								$.messager.alert({
									title: '成功',
									msg: '删除成功'
								});
								nextpage();
							} else {
								$.messager.alert({
									title: 'Error',
									msg: result.msg
								});
							}
						},
						'json');
				}
			});
		}

		function verifydata() { //审核
			if(isVerify == 1){
				$.messager.alert('警示', "该订单已审核，无需再审！");
				return;
			}
			if(currid == AddFlag) {
				$.messager.alert('警示', "当前页面为新增页面，不可审核！");
				return;
			}
			var a = checkDataIntegrity();
			if(a == 0) {
				$.messager.alert("提示", "请将页面中的数据补充完整后再进行审核！");
				return;
			}
			var _url = RemoteLinkAddress + "/logistics/writeoff/verify.do";
			$.ajax({
				dataType: 'JSON',
				url: _url,
				data: {
					ID: currid,
				},
				type: "POST",
				success: function(result) {
					$.messager.alert("成功", "审核成功");
					isVerify = 1;
					verifyStatus(isVerify, true);
				},
				error: function(result) {
					$.messager.alert("失败", "审核失败");
				}
			});
		}

		function unverifydata() { //弃审单据
			if(_dataPage.ISVERIFY == 0) {
				$.messager.alert("提示", "该订单已弃审！无需再弃审！");
				return;
			}
			$.messager.confirm("警告", "你确认要弃审该条单据吗", function(r) {
				if(r) {
					var _url = RemoteLinkAddress + "/logistics/writeoff/unverify.do";
					$.ajax({
						dataType: 'JSON',
						url: _url,
						data: {
							ID: currid,
						},
						type: "POST",
						success: function(result) {
							$.messager.alert("成功", "弃审成功");
							_dataPage.ISVERIFY = "0";
							isVerify = 0;
							verifyStatus(isVerify, true);
						},
						error: function(result) {
							$.messager.alert("失败", "弃审失败");
						}
					});
				}
			});
		}

		function searchmore() { //查询
			AddTabIn("冲销帐查询", parent.$('#tabs'), "UI/LOGISTICS/WriteOff/WriteOffSearch.html");
		}

		function print() { //打印
			var pLocation = "";
			if(currid == AddFlag) {
				$.messager.alert('警示', "当前页面为新增页面，不可打印！");
				return;
			}
			if(isVerify == 0) {
				$.messager.alert("警告", "该单据未审核不能打印");
				return;
			}
			pLocation = "WriteOffPrint.html?id=" + currid;
			window.open(pLocation);
		}

		function GetDetailTable() {
			$('#tt').edatagrid({
				height: 310,
				toolbar: _detailToolbarData,
				collapsible: 'true', //是否折叠：是
				singleSelect: 'true', //是否单选：是
				rownumbers: 'true',
				fitColumns: 'true', //自动调整列：是
				showFooter: 'true',
				autoSave: 'true',
				columns: [
					[{
						field: 'ID',
						title: 'ID',
						width: '0%',
						align: 'center'
					}, {
						field: 'ORDER_ID',
						title: '冲销单ID',
						width: '0%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "ORDER_ID",
								textField: "ORDER_ID",
								editable: false
							}
						}
					}, {
						field: 'STOREHOUSE_ID',
						title: '库房编号',
						width: '0%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "STOREHOUSE_ID",
								textField: "STOREHOUSE_ID",
								editable: false
							}
						}
					}, {
						field: 'STOREHOUSE_NAME',
						title: '库房名称',
						width: '13%',
						align: 'center',
						editor: {
							type: 'combobox',
							options: {
								valueField: 'NAME',
								textField: 'NAME',
								panelHeight: 'auto',
								mode: 'remote',
								method: 'get',
								url: RemoteLinkAddress + "/logistics/storehouse/listall.do",
								required: true,
								onSelect: function(record) {
									storehousename = record.NAME;
								}
							}
						}
					}, {
						field: 'INTERNALTRADE_ID',
						title: '内部商品ID',
						width: '0%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "INTERNALTRADE_ID",
								textField: "INTERNALTRADE_ID",
								editable: false
							}
						}
					}, {
						field: 'INTERNAL_NAME',
						title: '内部商品名',
						width: '14%',
						align: 'center',
						editor: {
							type: 'combobox',
							options: {
								valueField: 'INTERNAL_NAME',
								textField: 'INTERNAL_NAME',
								required: true,
								panelWidth: 200,
								panelHeight: 'auto',
								mode: 'remote',
								method: 'get',
								onChange: function(newValue, oldValue) {
									if(!isEnglish(newValue))
									{
										return;
									}
									if(newValue != "" && newValue != undefined) {
										var url = RemoteLinkAddress + "/logistics/internaltrade/findbypinyin?PINYINFIELDNAME=" + newValue.trim();
										$(this).combobox("reload", url);
									}
								},
								onSelect: function(record) {
									console.log(record);
									var _url = RemoteLinkAddress + "/logistics/warehouse/list.do?STOREHOUSE_NAME=" + storehousename + "&INTERNAL_NAME=" + record.INTERNAL_NAME;
									console.log(_url);
									$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
										type: "get",
										url: _url,
										dataType: "json",
										success: function(result) {
											var s = result.rows;
											console.log(s);
											var rowIndex = $("#tt").datagrid('getRowIndex', currRow);
											if(result.rows.length==0) {
												$.messager.alert('警示', "该仓库没有此类商品！");
												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'INTERNAL_NAME'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', '');
												return;
											}
											if(result != null) {
												var s = result.rows;
												var rowIndex = $("#tt").datagrid('getRowIndex', currRow);
												console.log(rowIndex);
												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'OLDSTOCK'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', result.rows[0].STOCK);

												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'STOREHOUSE_NAME'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', result.rows[0].STOREHOUSE_NAME);

												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'UNIT_NAME'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', record.UNIT_NAME);

												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'INTERNAL_TYPE'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', record.INTERNAL_TYPE);

												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'INTERNALTRADE_ID'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', result.rows[0].INTERNALTRADE_ID);

												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'STOREHOUSE_ID'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', result.rows[0].STOREHOUSE_ID);

												var target = $('#tt').datagrid('getEditor', {
													'index': rowIndex,
													'field': 'ORDER_ID'
												}).target;
												target.textbox('clear');
												target.textbox('setValue', currid);
											}
										},
										error: function(xhr, status, error) {
											$.messager.alert("错误", "请求失败!");
										}
									});
								}
							}
						}
					}, {
						field: 'INTERNAL_TYPE',
						title: '内部商品类型',
						width: '14%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "INTERNAL_TYPE",
								textField: "INTERNAL_TYPE",
								editable: false
							}
						}
					}, {
						field: 'OLDSTOCK',
						title: '原库存量',
						width: '14%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "OLDSTOCK",
								textField: "OLDSTOCK",
								editable: false
							}
						}
					}, {
						field: 'UNIT_NAME',
						title: '单位',
						width: '12%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "UNIT_NAME",
								textField: "UNIT_NAME",
								editable: false
							}
						}
					}, {
						field: 'TYPE',
						title: '冲销类型',
						width: '13%',
						align: 'center',
						editor: {
							type: 'combobox',
							options: {
								valueField: 'NAME',
								textField: 'NAME',
								required: true,
								data: [{
									NAME: '冲正',
									NAME: '冲正'
								}, {
									NAME: '销负',
									NAME: '冲负'
								}]
							},
							onSelect: function(record) {
								console.log(record);
							}
						}
					}, {
						field: 'WRITEOFFSTOCK',
						title: '冲销量',
						width: '14%',
						align: 'center',
						editor: {
							type: 'textbox',
							options: {
								valueField: "WRITEOFFSTOCK",
								textField: "WRITEOFFSTOCK",
								required: true
							}
						}
					}]
				],
				onEndEdit: function(index, row, changes) {
					console.log(row);
					if(row.TYPE == 1 && row.WRITEOFFSTOCK > row.OLDSTOCK) {
						$.messager.alert('警示', "仓库内该商品库存量不足！");
						row.WRITEOFFSTOCK = "";
					}

				},
				onDblClickRow: function(index, row) {
					currRow = row;
				},
				onAdd: function(index, row) {
					currRow = row;
				}
			});
		}

		function checkDataIntegrity() {
			var rowsdata = $("#tt").datagrid('getRows');
			console.log(rowsdata.length);
			if(rowsdata.length != 0) {
				for(var i = 0; i < rowsdata.length; i++) {
					var storehousename = rowsdata[i].STOREHOUSE_NAME;
					var internalname = rowsdata[i].INTERNAL_NAME;
					var internaltype = rowsdata[i].INTERNAL_TYPE;
					var unitname = rowsdata[i].UNIT_NAME;
					var oldstock = rowsdata[i].OLDSTOCK;
					var type = rowsdata[i].TYPE;
					console.log(storehousename + " " + internalname + " " + internaltype + " " + unitname + " " + oldstock + " " + type);
					var writeoffstock = rowsdata[i].WRITEOFFSTOCK;
					console.log(writeoffstock);
					if(storehousename == "" || internalname == "" || internaltype == "" || unitname == "" || oldstock === "" || type === "" || writeoffstock === "") {
						console.log("错误");
						return 0;
					}
				}
			} else {
				return 0;
			}
		}

		function exportExcel() {
			if(currid === AddFlag) {
				$.messager.alert("警告", "该订单为新增订单，无法导出Excel！");
				return;
			}
			$.messager.confirm("提示", "确认导出Excel表格吗？", function(r) {
				if(r) {
					$.ajax({ //调用ajax方法，从服务器获取到该订单的所有数据
						type: "get",
						dataType: "json", //服务器返回的数据类型
						url: RemoteLinkAddress + "/logistics/writeoff/excelorder.do",
						data: {
							"ID": _dataPage.ID
						},
						success: function(result) {
							window.location.href = result.path;
						}, //请求成功后，接受服务器传来的Json字符串，并做相应的处理
						error: function(xhr, status, error) {
							$.messager.alert("错误", "请求失败!");
						}
					});
				}
			});
		}
	</script>

</html>